/**
 * Created by IntelliJ IDEA.
 * User: Tracy.Think
 * Date: 12-8-24
 * Time: 下午3:46
 * 函数骨架
 */
/*
 This file depends on Ext JS 4.1 Ref Copyright (c) 2011-2012 Sencha Inc
 Contact:  Schiffer3rd@gmail.com
 */

/*
1ST Abstract ANALYSIS:
从普通业务逻辑对应的执行代码段 提取正确且可标准化的执行路径以封装,抽象了函数实现,使关注点为参数;
 动词(函数调用) 与 产生后果;操作前相关对象，操作后相关对象。
抽象的是普通经常性业务流程(某一种函数的具体代码，弱点，抽象粒度教细)，而非Component对象的行为.


2ND SAY: 全局性或外部对象(存在使用  全局性或外部对象  与  Component对象的 协同)，不易归纳，以函数过程来管理值周期,
         将 全局性或外部对象 值变化嵌入 动作(函数过程)。

3RD PS:JavaScript common value & Object

4TH Function Enumerate
  Value Reset:  Components'（Form,GridPanel's data (store) ） all value reset. store.removeAll(false); form.reset();

一 POP_MESSAGE： 上下文无状态。
二 SHOW:     Window
三 CLOSE:   Window
四 Refresh: Components refresh--->Components status lose(reset)--->Sub Components status lose(reset)
            Reverse code direction
五 Request(<Submit> uri)--Refresh---MSG
六 Cancel
七 CONFIRM
*/


/*Technology development：change mapping between request & HTTPMethod   415*/
var REQUEST_METHOD={create:"POST",modify:"PUT",delete:"DELETE",get:"GET",query:"POST",export:"GET",trig:"put"};

/***
 * Condition : Response code only single value  &  server  response vo contains boolean property "success"
 *
 * @param theForm
 * @param theConstructedRequestObject (the request object mapping server vo(entity),suggest implement the function 'construct??VO(theForm)')
 * @param uri
 * @param theMessageChain (ARRAY,index 0 place success message,index 1 place fail message)
 * @param invokeRefreshComponent (function pointer : refreshComponent)
 * @param invokeCloseWindow (function pointer : closeWindow)
 * @param theActionType  REQUEST_METHOD Enumerate
 */
function invokeRequest(theConstructedRequestObject,uri,theForm,theMessageChain,invokeRefreshComponent,invokeCloseWindow,theActionType){

    /*fireDynamicVerification(theForm):activate disable fragment*/
    if(!theForm.isValid()){ return;}

    Ext.Ajax.request({url:uri,
                      method:theActionType,
                      jsonData:theConstructedRequestObject,
                      timeout : 360000,
        success:function(serverResponse) {
            if(true==Ext.decode(serverResponse.responseText).success){
                if(invokeRefreshComponent!=null && invokeRefreshComponent!=undefined){invokeRefreshComponent();}
                if(invokeCloseWindow!=null && invokeCloseWindow!=undefined){invokeCloseWindow();}
                if(theMessageChain!=null && theMessageChain.length>0 ){popMessage(theMessageChain[0]);}
                else{popMessage(CONSTANT_COMMON_I18N.msg_action_success); }
            }
            else{
                if(theMessageChain!=null && theMessageChain.length>1 ){popMessage(theMessageChain[1]);}
                else{popMessage(CONSTANT_COMMON_I18N.msg_action_fail); }
            }
        },
        failure:function(response, opts) {
              popFailureMessage(CONSTANT_COMMON_I18N.msg_inputfield_error + " Status:" + response.status);
        }
      });

}

/***
 * invokeRequest specifically for delete
 * @param uri
 * @param theMessageChain(ARRAY,index 0 place success message,index 1 place fail message)
 * @param invokeRefreshComponent(function pointer : refreshComponent)
 * @param theActionType REQUEST_METHOD Enumerate
 */
function invokeDeleteRequest(uri,theMessageChain,invokeRefreshComponent,theActionType){
    Ext.Ajax.request({url:uri,
                      method:theActionType,
        success:function(serverResponse) {
            if(true==Ext.decode(serverResponse.responseText).success){
                if(invokeRefreshComponent!=null && invokeRefreshComponent!=undefined){invokeRefreshComponent();}
                if(theMessageChain!=null && theMessageChain.length>0 ){popMessage(theMessageChain[0]);}
                else{popMessage(CONSTANT_COMMON_I18N.msg_action_delete_success); }
            }
            else{
                if(theMessageChain!=null && theMessageChain.length>1 ){popMessage(theMessageChain[1]);}
                else{popMessage(CONSTANT_COMMON_I18N.msg_action_fail); }
            }
        },
        failure:function(response, opts) {
            popFailureMessage(CONSTANT_COMMON_I18N.msg_inputfield_error + " Status:" + response.status);
        }
    });

}



/***
 * pop window ,input query condition & then query.
 * @param theStore  data ref store, use Ext.data.Store.
 * @param theWindow
 * @param theForm
 * @param theResetStatus(Boolean)
 * @param invokeSetParams(function pointer,set proxy extraParams)
 */
function invokeQueryRequest(theStore,theWindow,theForm,theResetStatus,invokeSetParams){
    if(!theForm.isValid()){return;}
    invokeSetParams();
    theStore.loadPage(CONSTANT_COMMON_I18N.FIRST_PAGE);
    if(theResetStatus){theForm.reset();}
    if(theWindow!=null && theWindow!=undefined){theWindow.hide();}

}

    /*       TODO
function invokeQueryRequest(uri,....){

}
     */


/***
 * show condition verify,need form value reset, title change，bind form data, manual assign value,show
 * @param theWindow
 * @param theForm
 * @param theResetStatus(Boolean)
 * @param theTitle
 * @param theBindData(Ext.data.Model)
 * @param theVerifyChain(boolean value array ,verifyConditionFunction return value)
 * @param theVerifyMessageChain(ARRAY,match theVerifyChain)
 * @param theManualProcedure(function pointer)
 *         The function improve display of the window(form),
 *         For example :special value set, activate or disable form fragment 。
 */
function showWindow(theWindow,theForm,theResetStatus,theTitle,theBindData,theVerifyChain,theVerifyMessageChain,invokeManualProcedure){
    if(theVerifyChain!=null && theVerifyChain.length>0 ){
        for(var step=0;step<theVerifyChain.length;step++){
            if(theVerifyChain[step]==false){
                popMessage(theVerifyMessageChain[step]);return;
            }
        }
     }

    if(theResetStatus){theForm.reset();}
    if(theTitle!=null && theTitle!==''){theWindow.setTitle(theTitle);}
    /*fireDynamicVerification(theForm):activate disable fragment*/
    if(theBindData!==null){theForm.loadRecord(theBindData);}
    if(invokeManualProcedure!=null && invokeManualProcedure!=undefined){invokeManualProcedure();}
    theWindow.show();
}

/***
 * PS Idea : according Ext component type(Components enumerate:Window Form GridPanel)
 * @param theMainStore
 * @param theRefForms(ARRAY)
 * @param theSubStores(ARRAY)
 * @param invokeCustomerElementProcedure(function pointer): possible Ext.data.Model(Record) object，anyId,type
 */
function refreshComponent(theMainStore, theRefForms, theSubStores,invokeCustomerElementProcedure) {
    theMainStore.load();
    if (theRefForms != null && theRefForms.length > 0) {
        for (var step = 0; step < theRefForms.length; step++) {
            theRefForms[step].reset();
        }
    }
    if (theSubStores != null && theSubStores.length > 0) {
        for (var step = 0; step < theSubStores.length; step++) {
            theSubStores[step].removeAll(false);
        }
     }

    if(invokeCustomerElementProcedure!=null && invokeCustomerElementProcedure!=undefined){invokeCustomerElementProcedure();}
}


/***
 *
 * @param thePromptedName
 * @param theVerifyChain(boolean value array ,verifyConditionFunction return value)
 * @param theVerifyMessageChain(ARRAY,match theVerifyChain)
 * @param invokeDelete (implement like demo function deleteXXXX)
 */
function deleteConfirm(thePromptedName ,theVerifyChain,theVerifyMessageChain,invokeDelete) {
    if(theVerifyChain!=null && theVerifyChain.length>0 ){
        for(var step=0;step<theVerifyChain.length;step++){
            if(theVerifyChain[step]==false){
                popMessage(theVerifyMessageChain[step]);return;
            }
        }
    }

    var deleteTip = Ext.String.format(CONSTANT_COMMON_I18N.msg_confirm_delete_staff, thePromptedName);
    Ext.Msg.confirm(CONSTANT_COMMON_I18N.lab_system_alert, deleteTip, invokeDelete);
}


/***
 *  Demo Function
 * @param bid
 */
/*
function deleteXXXX(bid){
    if (bid == 'yes') {
        var uri = securedroot + '????/' + deleteId;
       invokeDeleteRequest(uri,theMessageChain,invokeRefreshComponent,REQUEST_METHOD.delete      );
     }

}
 */


/***
 *
 * @param theWindow
 * @param theForm
 */
function closeWindow(theWindow,theForm){
    theForm.reset();
    theWindow.hide();
}

/***
 * POP MESSAGE
 * @param i18nmsg
 */
function popMessage(i18nmsg) {
    Ext.Msg.show({title:CONSTANT_COMMON_I18N.lab_system_alert,msg: i18nmsg,buttons:Ext.Msg.OK, icon:Ext.Msg.INFO});
}

function popFailureMessage(i18nmsg) {
    Ext.MessageBox.show({title:ORCH_CLIENT_COMMON_I18N.lab_system_alert,msg:i18nmsg,buttons:Ext.MessageBox.OK,icon:Ext.MessageBox.ERROR});
}

var EXT_X_TYPE={form:"form",                 window:"window",             gridPanel:"gridpanel",
    textField:"textfield",      numberField:"numberfield",  dateField:"datefield",
    hiddenField:"hiddenfield",  comboBox:"combobox",         checkBoxField:"checkboxfield"
};

var CONSTANT_COMMON_I18N = {
    lab_system_alert : "系统提示",
    msg_action_success : "数据操作成功！",
    msg_action_delete_success : "数据删除成功！",
    msg_action_fail : "数据操作失败，请检查输入信息！",
    msg_inputfield_error : "输入信息有误，请检查！",
    msg_confirm_delete_staff:'确认删除 {0} 吗？',
    FIRST_PAGE : 1,
    TOBE : "TOBE"
}
